package main

import (
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"strconv"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.POST("/upload", func(c *gin.Context) {
		// 获取前端传文件
		file, err := c.FormFile("file")
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "文件上传失败"})
			return
		}
		// 获取前端传来 UID
		uidStr := c.PostForm("uid")
		uid, err := strconv.Atoi(uidStr)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户 UID"})
			return
		}
		// 构建保存文件路径
		uploadDir := fmt.Sprintf("uploads/%d", uid)
		err = os.MkdirAll(uploadDir, os.ModePerm)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "无法创建文件夹"})
			return
		}
		// 保存
		filePath := filepath.Join(uploadDir, file.Filename)
		if err := c.SaveUploadedFile(file, filePath); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "无法保存文件"})
			return
		}
		// 构建文件访问地址
		fileURL := fmt.Sprintf("/upload/%d/%s", uid, file.Filename)
		c.JSON(http.StatusOK, gin.H{"message": "文件上传成功", "file_url": fileURL})
	})
	r.Static("/upload", "./upload")
	// 设置静态文件路由
	r.Run(":3013")
}
